package service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.kwshare.common.core.domain.system.LoginInfo;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.*;

/**
 * ElasticSearch
 *
 * @author yangjing
 */
public class ElasticSearchService {

    public static void saveLoginInfo(LoginInfo loginInfo) throws Exception{
        //创建ES客户端
        RestClientBuilder httpClientBuilder = RestClient.builder(
                new HttpHost("localhost", 9200,"http")
        );
        RestHighLevelClient esClient = new RestHighLevelClient(httpClientBuilder);
        IndexRequest request = new IndexRequest();
        request.index("logininfo");
        String json = new ObjectMapper().writeValueAsString(loginInfo);
        request.source(json, XContentType.JSON);
        esClient.index(request, RequestOptions.DEFAULT);
        // 关闭连接
        esClient.close();
    }

    public static Map<String, Object> saveLoginInfo(int pageNum,int pageSize) throws IOException {
        //创建ES客户端
        RestClientBuilder httpClientBuilder = RestClient.builder(
                new HttpHost("localhost", 9200,"http")
        );
        RestHighLevelClient esClient = new RestHighLevelClient(httpClientBuilder);
        SearchRequest request = new SearchRequest();
        request.indices("logininfo");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        // （当前页码-1）*页面大小
        builder.from((pageNum-1)*pageSize);
        builder.size(pageSize);
        request.source(builder);
        builder.sort("loginTime", SortOrder.DESC);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        for (SearchHit hit : hits) {
            Map<String, Object> m = hit.getSourceAsMap();
            list.add(m);
        }
        map.put("data",list);
        // 关闭连接
        esClient.close();
        return map;
    }
}
